<template>
	<view class="bj-box left clearfix">
		<view class="bj-title left">
			背景音乐
		</view>
		<!--选项卡开始-->
		<view class="bj-label left clearfix">
			<view class="tim-type-item left" @click="timbreType = 1" :style="timbreType==1?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none;'">
				智能匹配
			</view>
			
			<view class="tim-type-item left" @click="selectedBackgroundMusic()" :style="timbreType==2?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none;'">
				手动选择
			</view>
			
			<view class="tim-type-item left" @click="uploadBackgroundMusic()" :style="timbreType==3?'background:#fff;border-radius:7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);color:#333;font-weight:500;':'background:none;border-radius:0;box-shadow: none'">
				本地上传
			</view>
		</view>
		
		<!--手动选择背景音乐弹窗-->
		<uni-popup type="center" ref="selectMusic">
			<view class="select-music-box left clearfix">
				<view class="timbre-title-box left clearfix">
					<view class="timbre-title-text left">
						选择背景音乐
					</view>
					<view class="timbre-title-close right" @click="closePopup()">
						<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
					</view>
				</view>
				
				<view class="music-title-label left clearfix">
					<label v-for="(item,index) in musicClass" :style="currentMusicClass == item._id?'border-bottom:3px solid #f3a73f':'border:none'" @click="getMusic(item._id)">{{item.title}}</label>
				</view>
				<view class="music-content left clearfix">
					
					<!--音乐循环列表-->
					<view class="music-item-box left clearfix" @click="selectedMusic(item,index)" @mouseenter="setPlay(item,index,'play')" @mouseleave="setPlay(item,index,'stop')" v-if="music && music[0]" v-for="(item,index) in music">
						<view class="music-selected left">
							<uni-icons type="icon-chenggong" size="22" color="#eee" custom-prefix="iconfont" v-if="!currentSelectedMusic || (currentSelectedMusic && currentSelectedMusic._id!=item._id)"></uni-icons>
							<uni-icons type="icon-xuanzhong2" size="22" color="#2979ff" custom-prefix="iconfont" v-if="currentSelectedMusic && currentSelectedMusic._id==item._id"></uni-icons>
						</view>
						<view class="music-title left" v-if="currentPlayId!=item._id">
							{{item.title}}
						</view>
						<view class="music-title left" style="margin-top:-6px;" v-else-if="currentPlayId==item._id">
							<slider :value="duration" min="0" :max="itemDuration" @change="sliderChange" step="1" activeColor="#18bc37" backgroundColor="#ddd" block-color="#18bc37" block-size="10" />
						</view>
						<view class="music-time right">
							{{formatCountdown(item.duration)}}
						</view>
					</view>
					
					
					<view class="music-item-null left clearfix" v-else-if="loading==true">
						<view class="loader"></view>
					</view>	
					
					<view class="music-item-null left clearfix" v-else-if="loading==false">
						<view>
							<uni-icons type="icon-wujilu" size="50" color="#ddd" custom-prefix="iconfont"></uni-icons>
						</view>
						<view>
							暂无数据
						</view>
					</view>	
					
					
				</view>
				
				<view class="music-button left clearfix">
					
					<view class="music-buttons right" @click="closePopup()" style="border:1px solid #ccc;background:none;color:#666;padding:7px 18px;">
						关闭
					</view>
					
					
					<view class="music-buttons right" @click="submitSelect()">
						确定
					</view>
					
				</view>
				
				
			</view>
		</uni-popup>
		
		
		
		<!--手动上传背景音乐弹窗-->
		<uni-popup type="center" ref="uploadtMusic">
			<view class="select-music-box left clearfix">
				<view class="timbre-title-box left clearfix">
					<view class="timbre-title-text left">
						上传背景音乐
					</view>
					<view class="timbre-title-close right" @click="closeUploadPopup()">
						<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
					</view>
				</view>
				
				<view class="music-title-label left clearfix">
					<label :style="uploadType==1?'border-bottom:3px solid #f3a73f':'border:none'" @click="uploadType=1">我的素材</label>
					<label :style="uploadType==2?'border-bottom:3px solid #f3a73f':'border:none'" @click="uploadType=2">本地上传</label>
				</view>
				<view class="music-content left clearfix" v-if="uploadType == 1">
					
					<!--音乐循环列表-->
					<view class="music-item-box left clearfix" @click="selectedMusic(item,index)" @mouseenter="setPlay(item,index,'play')" @mouseleave="setPlay(item,index,'stop')" v-if="music && music[0]" v-for="(item,index) in material">
						<view class="music-selected left">
							<uni-icons type="icon-chenggong" size="22" color="#eee" custom-prefix="iconfont" v-if="!currentSelectedMusic || (currentSelectedMusic && currentSelectedMusic._id!=item._id)"></uni-icons>
							<uni-icons type="icon-xuanzhong2" size="22" color="#2979ff" custom-prefix="iconfont" v-if="currentSelectedMusic && currentSelectedMusic._id==item._id"></uni-icons>
						</view>
						<view class="music-title left" v-if="currentPlayId!=item._id">
							{{item.title}}
						</view>
						<view class="music-title left" style="margin-top:-6px;" v-else-if="currentPlayId==item._id">
							<slider :value="duration" min="0" :max="itemDuration" @change="sliderChange" step="1" activeColor="#18bc37" backgroundColor="#ddd" block-color="#18bc37" block-size="10" />
						</view>
						<view class="music-time right">
							{{formatCountdown(item.duration)}}
						</view>
					</view>
					
					
					<view class="music-item-null left clearfix" v-else-if="loading==true">
						<view class="loader"></view>
					</view>	
					
					<view class="music-item-null left clearfix" v-else-if="loading==false">
						<view>
							<uni-icons type="icon-wujilu" size="50" color="#ddd" custom-prefix="iconfont"></uni-icons>
						</view>
						<view>
							暂无数据
						</view>
					</view>	
					
					
				</view>
				
				
				<view class="music-content left clearfix" v-if="uploadType == 2">
					<view class="music-upload-box left" @click="uploadAudio()" v-if="uploadPercent == 0">
						<view>
							<uni-icons type="icon-shangchuan6" size="35" color="#00c296" custom-prefix="iconfont"></uni-icons>
						</view>
						<view style="color:#666;">
							上传文件
						</view>
						<view style="color:#999;">
							支持.mp3、wav，10MB内
						</view>
					</view>
					
					<view class="music-upload-box left" @click="uploadAudio()" v-if="uploadPercent > 0 && uploadPercent < 100">
						<zmt-circular-progress :percent="uploadPercent" style="margin-top:30px;"></zmt-circular-progress>
					</view>
					
					
				</view>
				
				
				
				<view class="music-button left clearfix">
					
					<view class="music-buttons right" @click="closeUploadPopup()" style="border:1px solid #ccc;background:none;color:#666;padding:7px 18px;">
						关闭
					</view>
					
					
					<view class="music-buttons right" @click="submitSelect()">
						确定
					</view>
					
				</view>
				
				
			</view>
		</uni-popup>
		
		
		<!--选择完以后展示结果-->
		<view class="music-result-box left clearfix" v-if="currentSelectedMusic && currentSelectedMusic._id">
			<view class="music-result-image left">
				<image src="/static/images/select-bj-music.png" style="width:40px;height:40px;"></image>
			</view>
			<view class="music-result-text left">
				<text class="ellipsis">{{currentSelectedMusic.title}}</text>
				<text>{{formatCountdown(currentSelectedMusic.duration)}}</text>
			</view>
			<view class="music-reault-mores right" @click="this.$refs.selectMusic.open()">
				<uni-icons type="icon-qiehuanx" color="#666" size="20" custom-prefix="iconfont"></uni-icons>
			</view>
		</view>
   </view>
</template>

<style scoped>
	.music-upload-box view:first-child{margin-top:30px;}
	.music-upload-box view{width:100%;line-height:30px;text-align: center;font-size:14px;color:#333;}
	.music-upload-box{width:200px;height:150px;margin-top:100px;margin-left:calc((100% - 200px)/2);cursor:pointer;background:#f8f8f8;border-radius: 10px;}
	.music-reault-mores{width:40px;height:40px;float:right;margin-left:40px;line-height:40px;text-align: center;margin-top:8px;cursor:pointer;}
	.music-result-text text:last-child{color:#666;}
	.music-result-text text:first-child{font-weight:500;color:#333;}
	.music-result-text text{float:left;width:100%;line-height:20px;}
	.music-result-text{width:200px;height:40px;margin-top:7.5px;margin-left:5px;}
	.music-result-image{width:40px;height:40px;margin:7.5px;overflow: hidden;}
	.music-result-box{width:calc(100% - 40px);margin-left:20px;margin-top:30px;height:55px;align-items: center;background: #fff;border: 1px solid #dcdfe6;border-radius: 4px;border-radius: 7px;box-shadow: 0 0 4px 0 rgba(0, 0, 0, .15);font-size: 12px;}
	.music-item-null view{width:100%;text-align: center;color:#999;line-height:40px;font-size:14px;}
	.music-item-null{width:100px;height:100px;margin-top:100px;margin-left:calc((100% - 100px)/2);}
	.music-title-label label{margin-left:10px;margin-right:10px;padding-left:10px;padding-right:10px;line-height:29px;font-size:14px;cursor:pointer;height:29px;float:left;}
	.music-title-label{width:100%;height:30px;border-bottom:1px solid #eee;margin-top:10px;}
	.music-buttons{padding:8px 18px;background:#2979ff;color:#fff;border-radius: 5px;margin-right:10px;margin-left:10px;font-size:14px;margin-top:5px;cursor:pointer;}
	.music-button{width:90%;height:40px;margin-left:5%;margin-top:10px;}
	.music-time{width:40px;font-size:14px;color:#999;}
	.music-title{width:calc(100% - 60px);line-height:30px;height:30px;font-size:14px;color:#666;margin-left:10px;}
	.music-selected{width:30px;height:30px;line-height:30px;text-align: center;}
	.music-item-box{align-items: center;background: #fff;border: 1px solid #dcdfe6;border-radius: 4px;display: flex;height: 44px;justify-content: space-between;overflow: hidden;padding: 0 5px;width: 280px;margin:14px;cursor:pointer;}
	.music-content{width:96%;height:400px;margin-left:2%;margin-top:20px;overflow: auto;}
	.timbre-title-close{width:30px;height:50px;line-height:50px;margin-right:5px;cursor:pointer;}
	.timbre-title-text{line-height:50px;margin-left:20px;font-size:14px;}
	.timbre-title-box{width:100%;height:50px;}
	.select-music-box{width:1000px;height:600px;background:#fff;border-radius: 12px;}
	.tim-type-item{width:calc(33% - 5px);height:35px;line-height:35px;margin:5px;margin-top:2.5px;margin-left:2.5px;margin-right:2.5px;cursor: pointer;position: relative;text-align: center;transition: color 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);font-size:13px;color:#666;}
	.bj-label{width:calc(100% - 40px);margin-left:20px;background-color: rgba(0, 0, 0, 0.04);height:40px;margin-top:20px;border-radius: 7px;}
	.bj-title{width:calc(100% - 40px);padding-left:20px;font-size:14px;}
	.bj-box{width:100%;min-height:100px;}
</style>

<script>
	var db = uniCloud.database();
	import common from '@/static/js/common.js';
	export default {
		name:"background-music",
		data() {
			return {
				uploadType:1,//手动上传时默认展开的分类
				timbreType:1,//默认为智能匹配
				musicClass:[],//分类
				music:[],
				currentMusicClass:null,//当前选中的分类
				loading:false,
				currentPlayId:null,
				duration:0,
				innerAudioContext:null,//音频播放事件
				itemDuration:0,//当前播放的音频时长
				currentSelectedMusic:null,//当前选中的音乐
				uploadPercent:0,//上的进度
				material:[]
			};
		},
		mounted() {
			this.getMusicClass();
		},
		props:['userinfo'],
		methods:{
			//关闭上传弹窗
			closeUploadPopup(){
				this.$refs.uploadtMusic.close();
			},
			//上传
			uploadAudio(){
				var that = this;
				uni.chooseFile({
				  count: 1,
				  type: 'all',
				  success (res) {
					  console.log('选择的文件',res);
				    // tempFilePath可以作为img标签的src属性显示图片
				    const tempFilePaths = res.tempFilePaths[0];
					const tempFiles = res.tempFiles[0];
					var extension = common.getFileExtension(tempFiles.name);
					if(tempFiles.size > 10240000){
						uni.showToast({
							title:'文件过大，超过10MB，请重新上传。',
							icon:'none',
							duration:3000
						})
						
						return false;
					}
					
					if(extension!='mp3' && extension!='wav'){
						uni.showToast({
							title:'文件类型错误，请修改后上传',
							icon:'none',
							duration:3000
						})
						
						return false;
					}
					
					const fileName = common.generateUUIDWithExtension(tempFiles.name);
					console.log('待上传文件',res);
					 uniCloud.uploadFile({
					        filePath: tempFilePaths,
					        cloudPath: fileName,
					        onUploadProgress: function(progressEvent) {
					          console.log(progressEvent);
					          var percentCompleted = Math.round(
					            (progressEvent.loaded * 100) / progressEvent.total
					          );
							  
							  that.uploadPercent = percentCompleted;
							  
					        },
					        success(result) {
								var filePath = result.fileID;
								that.uploadPercent = 0;
								that.$refs.uploadtMusic.close();
								//添加到我的素材
								that.addToMaterial(filePath,tempFiles);
							}
					      });
				  }
				})
			},
			//添加到素材库
			addToMaterial(filePath,tempFiles){
				var that = this;
				var data = {
					"duration": tempFiles.duration,
					"size": tempFiles.size,
					"title": common.getFileNameWithoutExtension(tempFiles.name),
					"url": filePath,
					"type": "background-audio",
					"uid": this.userinfo._id
				}
				
				db.collection('material').add(data).then(res=>{
					uni.showToast({
						title:'上传成功',
						icon:'none'
					})
					var id = res.result.id;
					that.getDuration(id,filePath,data);
				});
			},
			//获取和更新视频时长
			getDuration(id,url,data){
				var that = this;
				var audio =  uni.createInnerAudioContext();
				data._id = id;
				audio.src = url;
				audio.onCanplay(()=>{
					var duration = parseInt(audio.duration);
					db.collection('material').where({_id:id}).update({
						duration:duration
					}).then(res=>{
						data.duration = duration;
						that.currentSelectedMusic = data;
					});
				})
			},
			//手动上传弹窗
			uploadBackgroundMusic(){
				//查询我的素材
				var userinfo = this.userinfo;
				if(userinfo && userinfo._id){
					db.collection('material').where({uid:userinfo._id,type:'background-audio'}).get().then(res=>{
						console.log('我的素材',res);
						this.material = res.result.data;
					});
				}
				
				this.$refs.uploadtMusic.open();
			},
			//确定选中以后
			submitSelect(){
				var that = this;
				if(this.innerAudioContext){
					that.duration = 0;
					that.innerAudioContext.stop();
					that.innerAudioContext.destroy();
				}
				this.$emit('selected',this.currentSelectedMusic);
				this.closeUploadPopup();
				this.$refs.selectMusic.close();
			},
			//选中当前音乐
			selectedMusic(item,index){
				this.currentSelectedMusic = item;
			},
			//拖动滑块事件
			sliderChange(e){
				this.innerAudioContext.seek(parseInt(e.detail.value)); 
			},
			//设置播放
			setPlay(item,index,action){
				var that = this;
				
				if(action == 'play'){
					var itemDuration = that.music[index].duration;
					this.itemDuration = itemDuration;
					if(that.innerAudioContext){
						that.duration = 0;
						that.innerAudioContext.stop();
						that.innerAudioContext.destroy();
					}
					var innerAudioContext= uni.createInnerAudioContext();
					that.innerAudioContext = innerAudioContext;
					innerAudioContext.src = item.url;
					innerAudioContext.play();
					innerAudioContext.onPlay(()=>{
						innerAudioContext.onTimeUpdate(()=>{
							var duration = parseInt(innerAudioContext.currentTime);
							that.duration = duration;
							that.music[index].duration = itemDuration - duration;
						});
						
					})
					this.currentPlayId = item._id;
				}else if(action == 'stop'){
					that.music[index].duration = that.itemDuration;
					that.innerAudioContext.stop();
					that.currentPlayId = null;
					that.innerAudioContext.destroy();
					that.duration = 0;
				}
			},
			//获取背景音乐分类
			getMusicClass(){
				db.collection('music_class').where({is_show:true}).orderBy('sort asc').get().then(res=>{
					var data = res.result.data;
					this.musicClass = data;
					//查询查第一个分类下的音乐
					this.getMusic(data[0]._id);
				});
			},
			//获取音乐
			getMusic(cid){
				this.loading = true;
				this.currentMusicClass = cid;
				db.collection('music').where({type:cid}).orderBy('_id desc').get().then(res=>{
					var data = res.result.data;
					this.music = data;
					this.loading = false;
				});
			},
			//手动选择背景音乐
			selectedBackgroundMusic(){
				this.timbreType = 2;
				this.$refs.selectMusic.open();
			},
			//关闭背景音乐弹窗
			closePopup(){
				this.$refs.selectMusic.close();
			},
			/**
			 * 将整数秒转换为 分:秒 格式的倒计时字符串
			 * @param {number} totalSeconds - 总秒数
			 * @param {boolean} [padZero=true] - 是否在分钟/秒数小于10时补零
			 * @returns {string} 格式化的倒计时字符串，如 "3:45" 或 "03:45"
			 */
			formatCountdown(totalSeconds, padZero = true) {
			  // 计算分钟和秒数
			  const minutes = Math.floor(totalSeconds / 60);
			  const seconds = totalSeconds % 60;
			  
			  // 补零处理
			  const formatNum = (num) => padZero ? num.toString().padStart(2, '0') : num;
			  
			  return `${formatNum(minutes)}:${formatNum(seconds)}`;
			}

		}
	}
</script>
